package concurrency2;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

public class ExchangerDemo {

    private static final Exchanger exchanger = new Exchanger();

    public static void main(String[] args) throws InterruptedException {

        new Thread(() -> {
            try {
                System.out.println("这是A的数据，接收到来自另一个线程的数据：" + exchanger.exchange("来自A的数据"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();

        System.out.println("这个时候A是阻塞的，等待来自B的数据");

        TimeUnit.SECONDS.sleep(1);

        new Thread(() -> {
            try {
                System.out.println("这是B的数据，接收到来自另一个线程的数据：" + exchanger.exchange("来自B的数据"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();
    }

}
